package com.order.service.impl;

import com.order.dao.Cart;
import com.order.dao.Item;
import com.order.dao.Order;
import com.order.mapper.OrderMapper;
import com.order.service.CartService;
import com.order.service.DeskService;
import com.order.service.ItemService;
import com.order.service.OrderService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;
import java.util.Random;

@Slf4j
@Service
@AllArgsConstructor
public class OrderServiceImpl implements OrderService {

    private OrderMapper orderMapper;

    private CartService cartService;

    private DeskService deskService;

    private ItemService itemService;

    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
    @Override
    public int addOrder(int desk_id) {
        Random random = new Random();
        int randomNumber = random.nextInt(9000000) + 1000000;
        List<Cart> carts= cartService.getCarts(desk_id);
        double sum=0;
        for (Cart cart: carts) {
          sum=sum+cart.getTotal();
        }
        Order order=new Order();
        order.setO_id(randomNumber);
        order.setDesk(deskService.selectDesk(desk_id));
        order.setOrder_time(LocalDate.now());
        order.setStatus(0);
        order.setAll_price(sum);
        /*新增订单表*/
        int count = orderMapper.addOrder(order);
        log.info(count>0 ?"新增成功" :"新增失败");
        /*新增详情页*/
        for (Cart cart:carts) {
            Item item =new Item();
            item.setDish(cart.getDish());
            item.setOrder(order);
            item.setNum(cart.getNum());
            itemService.addItem(item);
        }
        /*删除购物车*/
        cartService.deleteCart(desk_id);
        return count;
    }

    @Override
    public int deleteOrder(int id) {
        return orderMapper.deleteOrder(id);
    }

    @Override
    public int updateOrder(int id) {
        return orderMapper.updateOrder(id);
    }

    @Override
    public List<Order> selectOrder(Order order) {
        return orderMapper.selectOrder(order);
    }

    @Override
    public Order getByDeskId(int desk_id) {
        return orderMapper.getByDeskId(desk_id);
    }

    @Override
    public List<Order> getOrders(Order order) {
        return orderMapper.getOrders(order);
    }
}
